<?php


namespace app\common\controller;

use think\App;
use think\Exception;
use think\exception\HttpResponseException;

class ApiController
{

    /**
     * 免鉴权 控制器: controller
     *
     * @var array
     */
    protected static $noLoginControllerMap = array(
        'sign',
<<<<<<< HEAD
        'user'
=======
        'taskrelease', 'taskuser'
>>>>>>> e49929ddd700cb8ead48eb1d6b543c6fd2a581e5
    );

    /**
     * 免鉴权 方法: controller.action
     *             User.Login
     * @var array
     */
    protected static $noLoginActionMap = array(
        'task.getreleaselist',
        'sign.uploadPic',
        'user.infoUpload'
    );

    protected $model;

    /**
     * 用户id
     *
     * @var
     */
    public $userId;

    /**
     * token key
     *
     */
    const TOKEN_NAME = 'party_token';


    public function __construct()
    {

        $this->init();
    }

    /**
     * 初始化方法
     *
     */
    public function init()
    {

        $this->checkLogin();
        $this->checkAuth();
    }

    /**
     * 登陆校验
     *
     * @param int $exit
     * @return bool
     */
    public function checkLogin($exit=1)
    {

        $is_pass = false;
        $controller = strtolower(request()->controller());
        $action = strtolower(request()->action());

        // 免登陆校验
        if(
            in_array($controller, self::$noLoginControllerMap) ||
            in_array($controller.'.'.$action, self::$noLoginActionMap)
        ) { return true; }

        try{
            $token = isset($_COOKIE[self::TOKEN_NAME]) ? $_COOKIE[self::TOKEN_NAME] : '';
            !empty($token) ?: $token = input(self::TOKEN_NAME, '');
            if(empty($token)){throw new Exception('token 不存在');
            }else{
                if(session('token') != $token){throw new Exception('token 无效');}
                $this->userId = session('user_id');
            }
        }catch (\Exception $e){
            !$exit ?: $this->_result(-1, $e->getMessage(), array());
        }

        return $is_pass;
    }

    /**
     * 设置token
     *
     * @param $user_id
     * @return bool
     */
    public function setToken($user_id)
    {

        $token = md5('party' .session_create_id());
        session('user_id', $user_id);
        session('token', $token);

        setcookie(self::TOKEN_NAME, $token);
        return true;
    }

    public function checkAuth()
    {}

    public function setAuth()
    {}

    /**
     * 返回 json 结果
     *
     * @param array $data
     * @param int $code
     * @param string $msg
     * @param array $headers
     */
    public static function _result($data=[], $code=0, $msg='success', $headers=[])
    {

        $result = array(
            'time' => time(),
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        );

        throw new HttpResponseException(
            response($result, 200, $headers, 'json')
        );
    }
}